<template>
  <button @click="loafWebCom('com-title','com-1')">
    点击加载互联网组件com-title 命名com-1
  </button>
  <button @click="activeComEmit('com-1','click')">
    触发组件com-1 elbtn事件
  </button>
  <p></p>
  <button @click="loafWebCom('com-title','com-2')">
    点击加载互联网组件com-title 命名com-2
  </button>
  <button @click="activeComEmit('com-2','click')">
    触发组件com-2 elbtn事件
  </button>
  <div style="display: flex;flex-direction: row;">
    <template v-for="(item, index) in state.commArr" :key="index">
      <component
          :is="item.name"
          :ref="
          (ref) => {
            if (ref) item.ref = ref
          }
        "
          v-bind="item.props"
      />
    </template>
  </div>
</template>

<script setup>
import {reactive} from "vue";
import {loadCommAndCss} from "./utils";

const state = reactive({
  commArr: [],
  elButRef: null,
})

function loafWebCom(name, customName) {
  loadCommAndCss(name, '/').then((comm) => {
    console.log(comm)
    if (!window.VueApp.component(comm.name)){
      window.VueApp.use(comm)
    }
    const item = {
      name,
      customName,
      ref: null,
      props: { title: customName, msg: '天王盖地虎', onElbtn: onElbtnCb, onUpdate: onUpdate}, //  ,
    }
    if(customName === 'com-2'){
      item.props = { title: customName, msg: '宝塔镇河妖', onElbtn: onElbtnCb2, onUpdate: onUpdate2}
    }
    state.commArr.push(item)
  })
}

/**
 * 根据组件自定义id 操作组件
 * @param {string} customName 组件自定义名称
 * @param {string} emitName 组件自定义事件名称
 */
function activeComEmit(customName, emitName){
  const comm = state.commArr.find((it) => it.customName === customName)
  if(comm){
    console.log(comm.ref)
    comm.ref[emitName]()
  }
}
// 组件1回调
function onElbtnCb(e){
  console.log(e)
  // 执行组件2的事件
  activeComEmit('com-2','click')
}
// 组件1更新回调
function onUpdate(e){
  console.log(e)
}
// 组件2回调
function onElbtnCb2(e){
  console.log(e,2)
  // 执行组件1的事件
  activeComEmit('com-1','click')
}
// 组件2更新回调
function onUpdate2(e){
  console.log(e,2)
}
</script>

<style>
</style>
